<template>
  <div>
    <div class="validate-input-container pb-3">
      <label for="exampleInputEmail1" class="form-label">{{ title }}</label>
      <input
        text="text"
        class="form-control"
        :class="{'is-invalid': error}"
        @blur="onValideInput"
        :value="modelValue"
        @input="onUpdateValue"
        v-bind="$attrs"
      >
      <span
        v-if="error"
        id="emailHelp"
        class="invalid-feedback">
        {{message}}
      </span>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, PropType, onMounted } from 'vue'
const emailReg = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
const numberReg = /^[0-9]*$/;
export interface RuleProp {
  type: 'required' | 'email' | 'number',
  message: string
}

export type RulesProps = RuleProp[];
import { emitter } from './devin-form.vue'

export default defineComponent({
  props: {
    rules: {
      type: Array as PropType<RulesProps>
    },
    modelValue: String,
    title: String
  },
  inheritAttrs: false,
  setup(props, context) {

    const inputRef = reactive({
      value: props.modelValue || '',
      message: '提示信息',
      error: false,
      email: ''
    })

    onMounted(() => {
      emitter.emit('item-created', onValideInput)
    })


    const onUpdateValue = (e: KeyboardEvent) => {
      const targetVal = (e.target as HTMLInputElement).value;
      inputRef.value = targetVal;
      context.emit('update:modelValue', targetVal)
    }

    const onValideInput = () => {
       let allPassed = props.rules?.every(rule => {
         let passed = true;
         inputRef.message = rule.message;
         switch(rule.type) {
           case 'required':
           passed = (inputRef.value.trim() !== '');
           break;

           case 'email':
           passed = emailReg.test(inputRef.value.trim());
           break;

           case 'number':
           passed = numberReg.test(inputRef.value.trim());
           break;

           default:
          break;
         }
         return passed;
       })
       if (!allPassed) {
         console.log('1', 1)
        //  context.attrs.placeholder = inputRef.message;
        //  context.emit('update:modelValue', inputRef.message)
       }
       inputRef.error = !allPassed;
       return allPassed


      //   console.log(inputRef, ':', emailReg.test(inputRef.value))
      // if (inputRef.value.trim() === '') {
      //   inputRef.error = true;
      //   inputRef.message = 'can not be empty'
      // } else if (!emailReg.test(inputRef.value.trim())) {
      //   console.log('---------------')
      //   inputRef.error = true;
      //   inputRef.message = '请输入正确的邮箱信息';
      // } else {
      //   inputRef.error = false;
      //   inputRef.message = '';
      // }
    }
    return {
     ...toRefs(inputRef),
     onValideInput,
     onUpdateValue
    }
  }
})
</script>
